﻿using CsvHelper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DM_TOOLS.Tools.DBC.DBCCSV
{
    /// <summary>
    /// 用于解析csv压缩文件的类
    /// </summary>
    public static class DBCCSVReader
    {
        // 流式读取压缩 CSV 文件
        public static IEnumerable<DBCCSVMappingClass> ReadCompressedCsvStream(string gzFilePath)
        {
            using (FileStream fileStream = new FileStream(gzFilePath, FileMode.Open, FileAccess.Read))
            using (GZipStream gzipStream = new GZipStream(fileStream, CompressionMode.Decompress))
            using (StreamReader reader = new StreamReader(gzipStream))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                foreach (var record in csv.GetRecords<DBCCSVMappingClass>())
                {
                    yield return record;
                }
            }
        }

        // 异步读取整个压缩 CSV 文件到内存
        public static async Task<List<DBCCSVMappingClass>> ReadCompressedCsvAllAsync(string gzFilePath)
        {
            using (FileStream fileStream = new FileStream(gzFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: true))
            using (GZipStream gzipStream = new GZipStream(fileStream, CompressionMode.Decompress))
            using (StreamReader reader = new StreamReader(gzipStream))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                // CsvReader 目前没有原生异步 GetRecords<T>()，所以先同步获取，然后异步返回 List
                var records = csv.GetRecords<DBCCSVMappingClass>().ToList();
                return await Task.FromResult(records);
            }
        }
    }
}
